class Program < ActiveRecord::Base
  has_many                :broadcasts
  has_and_belongs_to_many :replica_systems
  
  validates_presence_of   :short_description, :name

  acts_as_authorizable
  acts_as_taggable
  
  def authors
    self.has_authors
  end
  
  def find_where_program_is_replicated
    self.replica_systems
  end
  
  def find_where_program_is_not_replicated
    replication_systems = ReplicaSystem.find_remote_replication_systems
    active_replication_systems = self.find_where_program_is_replicated
    
    replication_systems.reject { |a| active_replication_systems.include? a }
  end
  
  def self.find_by_audio_asset(audio_asset)
    Program.find_by_sql "SELECT DISTINCT p.* FROM audio_assets_broadcasts as a, broadcasts as b, programs as p 
      where a.audio_asset_id = #{audio_asset.id} and b.id = a.broadcast_id and b.program_id = p.id order by p.name"
  end
  
  def self.search(keys)
    conditions = []    
    search_columns = %w(name short_description description)
    search_columns.each { |element| conditions << (element + " LIKE '%#{keys}%'") }
    
    Program.find :all, :conditions => conditions.join(' or '), :order => :name
  end
  
  
  def add_tags(tags)
    self.tag_list.add(tags)
  end
  
  # Instance method for retrieve tag_cloud
  def tag_cloud
    self.tag_list.blank? ? [] : self.tag_counts
  end
  
  # Class method for retrieve tag_cloud
  def self.tag_cloud
    self.tag_counts.blank? ? [] : self.tag_counts
  end
  
  def self.top_tagged(limit = 10)
    total = Program.tag_cloud.size
    return nil if total.zero?
    
    limit = (limit > total) ? total : limit
    
    Program.tag_cloud.sort_by(&:count).reverse[0..(limit - 1)]
  end
  
  def self.find_by_tags(tags)
    self.find_tagged_with tags
  end
  
  def self.find_recent(limit = 3)
    self.find :all, :order => 'created_at desc', :limit => limit
  end
  
  
  def can_be_replicated_by(user)
    return false if user.blank?
    user.is_administrator?
  end
  
  def is_updatable_by(user)
    return false if user.blank?
    user.has_role? Role::Editor or user.is_administrator?
  end
  
  def is_deletable_by(user)
    return false if user.blank?
    false
  end
  
  def self.is_readable_by(user, object = nil)
    return false if user.blank?
    true
  end
  
  def self.is_creatable_by(user)
    return false if user.blank?
    user.has_role? Role::Editor or user.is_administrator?
  end
  
end
